package com.ljl.ningwei.common.web;

import com.ljl.ningwei.common.exception.AbstractExcepiton;
import com.ljl.ningwei.common.result.Result;
import jakarta.validation.ConstraintViolationException;
import lombok.extern.slf4j.Slf4j;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.MissingServletRequestParameterException;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.RestControllerAdvice;
import org.springframework.web.method.annotation.MethodArgumentTypeMismatchException;

import java.util.stream.Collectors;

/**
 * 全局异常处理器
 */
@RestControllerAdvice
@Slf4j
public class GlobalExceptionHandler {

    // 处理其他异常
    @ExceptionHandler(Exception.class)
    public Result handleException(Exception e) {
        e.printStackTrace();
        log.info("处理统一异常信息为:[{}]", e.getMessage());
        return Result.error("系统异常:" + e.getMessage());
    }

    @ExceptionHandler(AbstractExcepiton.class)
    public Result handleException(AbstractExcepiton ex) {
        log.info("处理统一异常信息为:[{}]", ex.getErrorMessage());
        return Result.error(ex.getErrorMessage());
    }

    // 处理 @RequestParam 参数缺失
    @ExceptionHandler(MissingServletRequestParameterException.class)
    public ResponseEntity<String> handleMissingServletRequestParameterException(MissingServletRequestParameterException e) {
        String errorMessage = e.getParameterName() + " 参数不能为空";
        return new ResponseEntity<>(errorMessage, HttpStatus.BAD_REQUEST);
    }

    // 处理 @RequestParam 参数类型不匹配
    @ExceptionHandler(MethodArgumentTypeMismatchException.class)
    public ResponseEntity<String> handleMethodArgumentTypeMismatchException(MethodArgumentTypeMismatchException e) {
        String errorMessage = e.getName() + " 参数类型不匹配";
        return new ResponseEntity<>(errorMessage, HttpStatus.BAD_REQUEST);
    }

    // 处理方法级别校验失败（@RequestParam 参数校验）
    @ExceptionHandler(ConstraintViolationException.class)
    public ResponseEntity<String> handleConstraintViolationException(ConstraintViolationException e) {
        // 提取校验失败的信息
        String errorMessage = e.getConstraintViolations().stream()
                .map(violation -> violation.getPropertyPath() + ": " + violation.getMessage())
                .collect(Collectors.joining(", "));
        return new ResponseEntity<>(errorMessage, HttpStatus.BAD_REQUEST);
    }
}
